package com.rich.login.controller;


import com.alibaba.fastjson.JSONObject;
import com.rich.login.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.alibaba.fastjson.JSON.parseObject;

/**
 * @Author:张龙飞
 * 客户端微信登录
 * @Date:2021/8/13
 */
@RestController
@Slf4j
@RequestMapping(value = "/loginServlet")
public class UserController{
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping
    public void login(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取到code值
        String code = request.getParameter("code");
        //判断
        if (code == null) {
            throw new RuntimeException("用户禁止授权");
        }
        //获取到了code值，回调没有问题
        //定义地址
        String token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx7287a60bb700fd21&secret=1ef8755f92bebae8ad7bab432ba29cbf&code="
                + code + "&grant_type=authorization_code";
        //发送请求
//        String json = restTemplate.getForObject(token_url, String.class);
        JSONObject jsonObject = HttpClientUtils.httpGet(token_url);
        System.out.println(jsonObject);
        //获取到接口调用凭证
        //获取个人信息
        String user_url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + jsonObject.get("access_token") + "&openid=" + jsonObject.get("openid");
        //个人信息
//        String jsonStr1 = restTemplate.getForObject(user_url, String.class);
        JSONObject user = HttpClientUtils.httpGet(user_url);
        System.out.println(user);
        log.info("======"+user);
        redisTemplate.opsForValue().set(user.get("openid"),user);
        request.setAttribute("user",user);
        //用户头像地址
        try {
            request.getRequestDispatcher("main.html").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("微信扫描登陆异常");
        }
    }
}
